package com.kyxx.topics.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.activity.JoinMemberActivity;
import com.kyxx.topics.activity.MemberAddCardActivity;
import com.kyxx.topics.activity.MemberDeatailActivity;
import com.kyxx.topics.activity.UserLoginActivity2;
import com.kyxx.topics.adapter.MembershipCardAdapter;
import com.kyxx.topics.bean.MembershipCardBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.ScreenSizeUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.zxing.encode.EncodingHandler;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class MembershipCardFragment extends Fragment{
    @Bind(R.id.rv_card)
    RecyclerView rv_card;
    @Bind(R.id.swipe_card)
    SwipeRefreshLayout swipe_card;
    @Bind(R.id.iv_add_card)
    ImageView iv_add_card;
    private MembershipCardAdapter adapter;
    private List<MembershipCardBean> beanList;
    private Context ctx;
    private boolean isLoadingMore = false;
    private boolean isReFresh = false;
    private int page = 1;
    private View view;
    private static final int Notify = 1;
    private boolean isCache = false;

    @Nullable
    public View onCreateView(LayoutInflater paramLayoutInflater, @Nullable ViewGroup paramViewGroup, @Nullable Bundle paramBundle) {
        view = paramLayoutInflater.inflate(R.layout.frament_membership_card, paramViewGroup, false);
        ctx = getActivity();
        ButterKnife.bind(this, view);
        this.beanList = new ArrayList<>();
        logic();
        return this.view;
    }


    private void logic() {
        beanList.clear();
        rv_card.setLayoutManager(new LinearLayoutManager(ctx));
        adapter = new MembershipCardAdapter(ctx, beanList);
        adapter.addFooterView(getFootView(),0);
        rv_card.setAdapter(adapter);
        rv_card.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItem = ((LinearLayoutManager) rv_card.getLayoutManager()).findLastVisibleItemPosition();
                int totalItemCount = rv_card.getLayoutManager().getItemCount();
                if (lastVisibleItem >= totalItemCount - 2 && dy > 0) {  //还剩2个Item时加载更多
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        loadMore();
                    }
                }
            }
        });
        swipe_card.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        rv_card.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if (StringUtil.isEmpty(BaseApp.getModel().getId())) {
                    ToastUtils.show(ctx, "您未登录，请先登录");
                    startActivity(new Intent(ctx, UserLoginActivity2.class));
                } else {
                    startActivity(new Intent(ctx, MemberDeatailActivity.class).putExtra("bean", beanList.get(i)));
                }
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                switch (view.getId()) {
                    case R.id.rl_member_num:
                        if(beanList.get(position).getIs_member() == 1){
                            if(StringUtil.isChineseChar(beanList.get(position).getCardnum())||"".equals(beanList.get(position).getCardnum())){
                                if(StringUtil.isChineseChar(beanList.get(position).getMobile())||"".equals(beanList.get(position).getMobile())){
                                    ToastUtils.show(ctx,"请输入正确的会员卡号");
                                }else{
                                    dialog(beanList.get(position).getMobile());
                                }
                            }else{
                                dialog(beanList.get(position).getCardnum());
                            }
                        }else {
                            ctx.startActivity(new Intent(ctx,JoinMemberActivity.class).putExtra("CardBean", beanList.get(position)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                        }
                        break;
                }
            }
        });
//        refresh();
    }
    private View getFootView() {
        View view = LayoutInflater.from(ctx).inflate(R.layout.item_membership_card_footer, null);
        return view;
    }
    private void refresh() {
        this.isReFresh = true;
        this.page = 1;
        loadData(page);
    }

    private void loadMore() {
        isReFresh = false;
        page = page+1;
        loadData(page);
    }

    private void loadData(int page) {
        HttpParams params = new HttpParams();
        JSONObject obj = new JSONObject();
        obj.put("uid", BaseApp.getModel().getId());
        obj.put("page", page);
        params.put("json", obj.toString());
        OkGoRequest.post(UrlUtils.VIP_CARD, ctx, "vip_list", CacheMode.REQUEST_FAILED_READ_CACHE, params, new StringCallback() {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                isCache = true;
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    List<MembershipCardBean> bean = JSONObject.parseArray(result.getJSONArray("data").toString(), MembershipCardBean.class);
                    if (swipe_card.isRefreshing()) {
                        swipe_card.setRefreshing(false);
                    }
                    if (isReFresh||isCache) {
                        beanList.clear();
                    } else {
                        isLoadingMore = false;
                        isCache = false;
                    }
                    beanList.addAll(bean);
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.show(ctx, "网络错误请稍后再试");
            }
        });
    }

    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        OkGo.getInstance().cancelTag(ctx);
    }



    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    @OnClick(R.id.iv_add_card)
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_add_card:
                startActivity(new Intent(ctx, MemberAddCardActivity.class));
                break;
        }
    }
    private void  dialog(String code){
        Dialog dialog = new Dialog(ctx);
        View mDialogView =  View.inflate(ctx, R.layout.dialog_scan_code, null);
        ImageView img = (ImageView) mDialogView.findViewById(R.id.iv_scan_code);
        TextView tv = (TextView) mDialogView.findViewById(R.id.tv_scan_code_num);
        mDialogView.setMinimumHeight((int) (ScreenSizeUtils.getInstance(ctx).getScreenHeight() * 0.2f));
        dialog.setContentView(mDialogView);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(ctx).getScreenWidth() * 0.88f);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialogWindow.setAttributes(lp);
        img.setImageBitmap(createBarCode(code));
        tv.setText(code);
        dialog.show();
    }
    private Bitmap createBarCode(String key) {
        Bitmap qrCode = null;
        try {
            qrCode = EncodingHandler.createBarCode(key, (int) (ScreenSizeUtils.getInstance(ctx).getScreenWidth() * 0.7f), (int) (ScreenSizeUtils.getInstance(ctx).getScreenHeight() * 0.17f));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCode;
    }
}